package com.dahaiwuliang.code.controller.admin;

import com.dahaiwuliang.code.pojo.Link;
import com.dahaiwuliang.code.run.StartupRunner;
import com.dahaiwuliang.code.server.LinkService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping (value = "/admin/link")
public class LinkAdminController {
    @Autowired
    private LinkService linkService;

    @Autowired
    private StartupRunner startupRunner;


    /**
     * 分页查询
     */
    @RequestMapping(value = "/list")
    @RequiresPermissions (value = "分页查询友情链接")
    public Map<String,Object> list( @RequestParam (value = "page",required = false) Integer page,
                                    @RequestParam(value = "pageSize",required = false) Integer pageSize){
        Map<String,Object> resultMap=new HashMap<>();
        resultMap.put("data",linkService.list(page,pageSize,Sort.Direction.ASC,"sort"));
        resultMap.put("toral",linkService.getCount());
        resultMap.put("errorNo",0);

        return resultMap;
    }

    @RequestMapping(value = "/save")
    @RequiresPermissions (value = "添加或者修改友情链接")
    public Map<String,Object> save(@RequestParam(value = "linkId")Integer id,Link link){
        Map<String,Object> resultMap=new HashMap<>();
        linkService.save(link);
        startupRunner.loadData();
        resultMap.put("errorNo",0);
        return  resultMap;
    }

    @RequestMapping(value = "/findById")
    @RequiresPermissions (value = "根据id查询友情链接")
    public Map<String,Object> findById(@RequestParam(value = "linkId")Integer id){
        Map<String,Object> resultMap=new HashMap<>();
        resultMap.put("data",linkService.getById(id));
        resultMap.put("errorNo",0);
        return  resultMap;
    }

    /**
     * 批量删除资源
     */
    @RequestMapping(value = "/delete")
    @RequiresPermissions(value = "删除友情链接")
    public Map<String,Object> delete(@RequestParam(value = "linkId")String ids){
        Map<String,Object> resultMap=new HashMap<>();
        String[] idsStr=ids.split(",");
        for (int i=0;i<idsStr.length;i++){
            linkService.delete(Integer.parseInt(idsStr[i]));
        }
        startupRunner.loadData();
        resultMap.put("errorNo",0);
        return resultMap;
    }
}
